package cn.yogehaoren.confirm;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.ConfirmListener;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @author WangNing
 * @since 1.0
 */
public class ConfirmProducer {


    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("k8s-node2");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/");

        Connection connection = connectionFactory.newConnection();

        Channel channel = connection.createChannel();

        // 指定消息的确认模式
        channel.confirmSelect();

        String exchangeName = "test_confirm_exchange";
        String routingKey = "confirm_save";

        String msg = "Hello RabbitMQ send Confirm message!";
        for (int i = 0; i < 200; i++) {
            channel.basicPublish(exchangeName, routingKey, null, msg.getBytes());
        }


        // 添加监听器
        channel.addConfirmListener(new ConfirmListener() {
            // 成功处理，回调的方法
            @Override
            public void handleAck(long deliveryTag, boolean multiple) throws IOException {
                System.out.println(deliveryTag);
                System.out.println(multiple);
                System.out.println("----------------- ack -----------------");
            }

            // 失败回调的方法
            @Override
            public void handleNack(long deliveryTag, boolean multiple) throws IOException {
                System.out.println(deliveryTag);
                System.out.println(multiple);
                System.out.println("!!!!!!!!!!!!!!!!! no ack !!!!!!!!!!!!!!!!!");
            }
        });

        // 关闭连接，线程会退出，否则不会主动退出
        // channel.close();
        // connection.close();

    }


}
